package org.balthie.demo.jdk.nio.pipe;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

// 进程间通讯：管道
//https://blog.csdn.net/m0_52169086/article/details/125375655
public class PipeBlockedIODemo {
	public static void main(String[] args) {
		try {
			Pipe pipe = Pipe.open();

			Thread t1 = new Thread(() -> {
				sink(pipe);
			});
			Thread t2 = new Thread(() -> {
				source(pipe);
			});
			t1.start();
			t2.start();
//			t1.join();
//			t2.join();
			
			Thread.sleep(5000);
		} catch (IOException | InterruptedException e) {
			e.printStackTrace();
		}
	}

	private static void source(Pipe pipe) {
		Pipe.SourceChannel sourceChannel = pipe.source();
		ByteBuffer buf = ByteBuffer.allocate(256);
		try {
			int len = sourceChannel.read(buf);
			buf.flip();
			System.out.println(Thread.currentThread() + " sourceChannel read " + new String(buf.array(), 0, len));

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				sourceChannel.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private static void sink(Pipe pipe) {
		Pipe.SinkChannel sinkChannel = pipe.sink();
		ByteBuffer buf = ByteBuffer.allocate(256);
		buf.put("你好啊".getBytes());
		buf.flip();
		try {
			System.out.println(Thread.currentThread() + " sinkChannel write 你好啊" );
			sinkChannel.write(buf);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				sinkChannel.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
